package com.yunshang.shoppingmall.shopping.User;

import com.yunshang.shoppingmall.entity.*;

import com.yunshang.shoppingmall.service.AchievementCommissionService;
import com.yunshang.shoppingmall.service.Finace.FinaceService;
import com.yunshang.shoppingmall.service.Finace.FinaceTotalService;
import com.yunshang.shoppingmall.service.OrderService;
import com.yunshang.shoppingmall.service.SysUserNoService;
import com.yunshang.shoppingmall.service.User.UserRankService;
import com.yunshang.shoppingmall.service.UserNoAchievementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

@Controller
@RequestMapping("/wap")
public class UserNoAchievementController {
    @Autowired
    OrderService orderService;
    @Autowired
    SysUserNoService sysUserNoService;
    @Autowired
    UserNoAchievementService userNoAchievementService;
    @Autowired
    FinaceTotalService finaceTotalService;
    @Autowired
    FinaceService finaceService;
    @Autowired
    UserRankService userRankService;
    @Autowired
    AchievementCommissionService achievementCommissionService;

    @ResponseBody
    @RequestMapping("/getUserNoAchievement")
    public Map<String, Object> getUserNoAchievement(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        //每天
        Timestamp startTime = null;
        Timestamp endTime = null;
        String userNoId = request.getParameter("userNoId");
        String type= request.getParameter("type");
       switch (type){
           case "1":    startTime = new Timestamp(DateUtils.getDayBegin().getTime());
                        endTime = new Timestamp(DateUtils.getDayEnd().getTime());break;
           case "2":      Date date=new Date();
                           String date1=DateUtils.getTimeInterval(date);
                           String dateTime[]=date1.split(",");
                           startTime=Timestamp.valueOf(dateTime[0]);
                           endTime=Timestamp.valueOf(dateTime[1]);     break;
           case "3":  Date startMonth=DateUtils.getBeginDayOfMonth();
                      Date endMonth=DateUtils.getEndDayOfMonth();
                      startTime=new Timestamp(startMonth.getTime());
                      endTime=new Timestamp(endMonth.getTime());break;
       }

        if (userNoId == null || userNoId == "") {
            map.put("msg", "0");
            return map;
        }

        int userNoIds = Integer.parseInt(userNoId);
        UserNoAchievement userNoAchievement = new UserNoAchievement();
        userNoAchievement.setEndTime(endTime);
        userNoAchievement.setStartTime(startTime);
        userNoAchievement.setUserNoId(userNoIds);
        List<UserNo> userNoList = sysUserNoService.selectUserNoList();
        int recommendId = 0;
        UserNo userNo = null;
        double opratorCostSum = 0;
        double userOpratorcost=0;//用户原有的业绩
        double userWeekOpratorcost=0;//用户原有的周业绩
        double userMonthOpratorcost=0;//用户原有的月业绩

        //推荐人
        List<UserNo> recommendList = new ArrayList<>();
        for (int i = 0; i < userNoList.size(); i++) {
            System.out.println("useid"+userNoIds);
            userNoAchievement.setUserNoId(userNoIds);
            userNoAchievement.setOpratorCostSign("0");
            UserNo userNo1 = sysUserNoService.selectByPrimaryKey(userNoIds);
            if (userNo1== null) {
                break;
            }
           userOpratorcost= userNo1.getOrderOpratorcost();//用户当天的业绩
            userWeekOpratorcost=userNo1.getWeekOpratorcost();//用户周业绩
            userMonthOpratorcost=userNo1.getMonthOpratorcost();//用户月业绩
            opratorCostSum+=userNoAchievementService.orderOpratorCost(userNoAchievement);
            System.out.println("总："+opratorCostSum);
            //根新用户表的业绩
            UserNo userNo2=new UserNo();
            userNo2.setId(userNoIds);
            userNo2.setOrderOpratorcost(userOpratorcost+opratorCostSum);

            //更新用戶周业绩
            userNo2.setWeekOpratorcost(userWeekOpratorcost+opratorCostSum);
            userNo2.setMonthOpratorcost(userMonthOpratorcost+opratorCostSum);

            int row=sysUserNoService.updateByPrimaryKeySelective(userNo2);
            if(row>0){//更改业绩表的状态
                userNoAchievement.setOpratorCostSign("1");
                int achievementRow=userNoAchievementService.updataByUserNoId(userNoAchievement);
            }

            System.out.println("每个人业绩："+userNoIds+"----"+opratorCostSum);
            recommendId = userNo1.getRecommend();
            userNoIds = recommendId;
            System.out.println("业绩："+opratorCostSum);
            recommendList.add(userNo);
        }

        int userNoRecommendId = 0;
        List<UserNoAchievement> userNoAchievementList=null;
        System.out.println("推荐人："+recommendList.size());
        map.put("opratorCostSum", opratorCostSum);
        map.put("msg", "1");
        return map;
    }

    //查询用户业绩
    @ResponseBody
    @RequestMapping("/getUserNoOprator")
    public Map<String,Object> getUserNoOprator(HttpServletRequest request){
        Map<String,Object> map=new HashMap<>();
        String userNoId=request.getParameter("userNoId");
        int userNoIds=0;
        if(userNoId!=null&&userNoId!=""){
            userNoIds=Integer.parseInt(userNoId);
        }

        UserNo userNo=sysUserNoService.selectByPrimaryKey(userNoIds);
        map.put("userNo",userNo);
        map.put("msg","1");
        return map;
    }


    //业绩每个月转化给用户积分
     //每个月1号凌晨3点执行    @Scheduled(cron = "0 0 3 1 * ?")
    @Scheduled(cron = "0 50 16 2 * ?")
 public void SettlementPerformance(){
        double monthOpratorCost=0.00;
        int userNoId=0;
        UserNo userNo=null;
        int userNoRow=0;
        Calendar cale = null;
        cale = Calendar.getInstance();
        int year = cale.get(Calendar.YEAR);
        int month=cale.get(Calendar.MONTH)+1;
        //查询业绩提成比
        List<AchievementCommission> achievementCommissionList=achievementCommissionService.selectList();
        double achievementCommission=0.00;//提成比

    //查询用户表
    List<UserNo> userNoList=sysUserNoService.selectUserNoList();
        for (int i = 0; i <userNoList.size() ; i++) {
            if(userNoList==null||userNoList.get(i)==null){continue;}
            monthOpratorCost=userNoList.get(i).getMonthOpratorcost();
            if(monthOpratorCost==0){continue;}//月业绩为零的不更新操作
            //查询业绩等级提成比
            for (int j = 0; j <achievementCommissionList.size() ; j++) {
                if(monthOpratorCost<=achievementCommissionList.get(0).getAcAmount()){
                    achievementCommission=achievementCommissionList.get(0).getAcCommission();
                }else{
                    if(monthOpratorCost<achievementCommissionList.get(j).getAcAmount()){
                        achievementCommission=achievementCommissionList.get(j-1).getAcCommission();
                        System.out.println("----------achievementCommission---------------->"+achievementCommission);
                    }
                }
            }
            userNoId=userNoList.get(i).getId();
            //更新用户表的业绩归零
            userNo=new UserNo();
            userNo.setId(userNoId);
            userNo.setOrderOpratorcost(0.00);//当天业绩
            userNo.setWeekOpratorcost(0.00);//周业绩
            userNo.setMonthOpratorcost(0.00);//月业绩
            System.out.println("更新：------------------------->"+userNoId+"业绩："+monthOpratorCost);
            userNoRow=sysUserNoService.updateByPrimaryKeySelective(userNo);

            if(userNoRow>0){
                //查询该用户的积分余额
                FinaceTotal finaceTotalBlance=finaceTotalService.selectFinaceTotal(userNoId,"1");
                double balance=0.00;
                if(finaceTotalBlance!=null){
                     balance=finaceTotalBlance.getBalance();
                }
                FinaceTotal finaceTotal=new FinaceTotal();
                finaceTotal.setUserId(userNoId);

                //增加到积分表月业绩
                double achMonthOpratorCost=monthOpratorCost*achievementCommission/100.00;//按提成比计算后的月业绩
                finaceTotal.setBalance(balance+achMonthOpratorCost);
                finaceTotal.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                int totalRow=finaceTotalService.updateBalanceByUserIdAndFType(finaceTotal);

                FinaceToData finaceToData2 = new FinaceToData();
                finaceToData2.setUserId(userNoId);//用户编号Id
                finaceToData2.setFinaceType("222");
                finaceToData2.setRemark(year+"-"+month+"月业绩");
                finaceToData2.setClassify(1);
                finaceToData2.setFinaceTime(new Timestamp(System.currentTimeMillis()));//时间
                finaceToData2.setAmount(new BigDecimal(achMonthOpratorCost));
                finaceToData2.setBalance(new BigDecimal(balance+achMonthOpratorCost));

                int finaceRow = finaceService.insertFinaceData(finaceToData2);

            }
        }

 }

}
